﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public GameObject boom;
    public GameObject score;
    private SpriteRenderer render;
    public Sprite hurt_pic;
    public AudioClip audio_hurt;
    public AudioClip audio_dead;

    private void Awake()
    {
        render = GetComponent<SpriteRenderer>();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.relativeVelocity.magnitude >= 12)
        {
            Dead();
        }else if (collision.relativeVelocity.magnitude >6 && collision.relativeVelocity.magnitude < 12)
        {
            Hurt();
        }
    }

    public void Dead()
    {
        //销毁自己
        Destroy(gameObject);
        //实例化boom，位置与角度保持不变,动画结束后该对象由另一个脚本销毁
        //也可以用延时销毁，但不够精准
        Instantiate(boom,transform.position,Quaternion.identity);
        //实例化score，位置上移一点
        GameObject k = Instantiate(score, transform.position + new Vector3(0, 0.5f, 0), Quaternion.identity);
        //1.5秒后销毁
        Destroy(k,1.5f);
        GameManager._instance.pigs.Remove(this);
        AudioPlay(audio_dead);
    }

    private void Hurt()
    {
        render.sprite = hurt_pic;
        AudioPlay(audio_hurt);
    }

    private void AudioPlay(AudioClip clip) //声效音乐播放
    {
        //该音乐播放不受物体销毁的影响
        AudioSource.PlayClipAtPoint(clip, transform.position);
    }
}
